<?php

/**
 * CustomerController
 * 
 * @author
 * @version 
 */

require_once 'Zend/Controller/Action.php';

class CustomerController extends Zend_Controller_Action 
{
	protected $_model;
	protected $_authService;
	
	public function init()
	{
		$this->_model = new Eleven_Model_User();
		$this->_authService = new Eleven_Service_Authentication();
		
		$this->view->loginForm = $this->getLoginForm();
	}
	
    public function indexAction() 
	{
        $this->view->user = $this->_model->getUserById($this->_authService->getIdentity()->userId);

        if (null === $this->view->user) {
            throw new CMS_Exception('Unknown user');
        }
    }
	
	public function loginAction()
	{}
	
    public function authenticateAction()
	{
        $request = $this->getRequest();

        if (!$request->isPost()) {
            return $this->_helper->redirector('login');
        }

        // Validate
        $form = $this->_forms['login'];
        if (!$form->isValid($request->getPost())) {
            return $this->render('login');
        }
        
        if (false === $this->_authService->authenticate($form->getValues())) {
            $form->setDescription('Login failed, please try again.');
            return $this->render('login');
        }
        
        return $this->_helper->redirector('index','index');
	}
	
    public function getLoginForm()
    {
        $urlHelper = $this->_helper->getHelper('url');
        
        $this->_forms['login'] = $this->_model->getForm('userLogin');
        $this->_forms['login']->setAction($urlHelper->url(array(
            'controller' => 'customer',
            'action'     => 'authenticate',
            ), 
            'default'
        ));
        $this->_forms['login']->setMethod('post');
        
        return $this->_forms['login'];
    }
    
    public function logoutAction()
    {
        $this->_authService->clear();
        return $this->_helper->redirector('index','index');
    }

}